﻿namespace SecurePlayer
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Linq;
    using System.Management;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.ServiceModel;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    using Vlc.DotNet.Core.Medias;
    using Vlc.DotNet.Forms;
    using Vlc.DotNet.Core;
    using System.Text.RegularExpressions;
    using System.Net;
    using SecurePlayer.SecureService;

    public partial class VlcPlayer : Form
    {
        public PlayerPlugin Reference;
        private Chat frmChat;
        private IntPtr m_ip = IntPtr.Zero;
        private int intCacheSize = 0;
        private string SanukSourceID = string.Empty;

        public VlcPlayer()
        {
            // Set libvlc.dll and libvlccore.dll directory path
            VlcContext.LibVlcDllsPath = @"C:\Program Files (x86)\VideoLAN\VLC"; // CommonStrings.LIBVLC_DLLS_PATH_DEFAULT_VALUE_AMD64;

            // Set the vlc plugins directory path
            VlcContext.LibVlcPluginsPath = @"C:\Program Files (x86)\VideoLAN\VLC\pugins"; //CommonStrings.PLUGINS_PATH_DEFAULT_VALUE_AMD64;

            if (!Directory.Exists(VlcContext.LibVlcDllsPath))
            {
                // Set libvlc.dll and libvlccore.dll directory path
                VlcContext.LibVlcDllsPath = @"C:\Program Files\VideoLAN\VLC";
                VlcContext.LibVlcPluginsPath = @"C:\Program Files\VideoLAN\VLC\pugins";
            }

            if (!Directory.Exists(VlcContext.LibVlcDllsPath))
            {
                MessageBox.Show("VLC Player ist nicht installiert, bitte installieren Sie Ihn von www.videolan.org");
                System.Diagnostics.Process.Start("http://www.videolan.org");
            }

            // Ignore the VLC configuration file
            VlcContext.StartupOptions.IgnoreConfig = true;

            // Enable file based logging
            VlcContext.StartupOptions.LogOptions.LogInFile = false;

            // Shows the VLC log console (in addition to the applications window)
            VlcContext.StartupOptions.LogOptions.ShowLoggerConsole = false;

            // Set the log level for the VLC instance
            VlcContext.StartupOptions.LogOptions.Verbosity = VlcLogVerbosities.Debug;

            // Initialize the VlcContext
            VlcContext.Initialize();

            InitializeComponent();

            labelPlaybackPosition.Text = string.Empty;
            label2.Text = string.Empty;
            this.vlcControlMain.PositionChanged += this.VlcControlMain_OnPositionChanged;
            this.vlcControlMain.Playing += vlcControlMain_Playing;
            this.vlcControlMain.Stopped += vlcControlMain_Stopped; 
        }

        private delegate void ParseDataCallback(EventDataType Message);
        public void ParseData(EventDataType Data)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new ParseDataCallback(ParseData), Data);
            }
            else
            {
                string[] arr_szDataArray = Data.EventMessage.Split('|');
                switch (arr_szDataArray[0])
                {
                    case "Chat":
                        try
                        {
                            ChatNewMessage(Data.SourceClient, arr_szDataArray[1]);
                        }
                        catch (Exception)
                        {
                        }
                        break;
                    case "SetPowerLevel":
                        try
                        {
                            int SanukPowerlevel = int.Parse(arr_szDataArray[1]);
                            SanukSourceID = Data.SourceClient;
                            trackBar1.Enabled = true;
                            MaxPowerLevel(SanukPowerlevel);
                        }
                        catch (Exception)
                        {
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        #region Events

        private void vlcControlMain_Playing(VlcControl sender, VlcEventArgs<EventArgs> e)
        {
            this.buttonConnect.Enabled = false;
            this.buttonStop.Enabled = true;
        }

        private void vlcControlMain_Stopped(VlcControl sender, VlcEventArgs<EventArgs> e)
        {
            this.buttonStop.Enabled = false;
            this.buttonConnect.Enabled = true;
        }

        private void VlcControlMain_OnPositionChanged(VlcControl sender, VlcEventArgs<float> e)
        {
            labelPlaybackPosition.Text = (e.Data * 100).ToString("000") + " %";
        }

        private void ButtonStopClick(object sender, EventArgs e)
        {
            this.vlcControlMain.Stop();
        }

        public delegate void VlcPlayer_FormClosing_Callback(object sender, FormClosingEventArgs e);
        public void VlcPlayer_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new VlcPlayer_FormClosing_Callback(VlcPlayer_FormClosing), sender, e);
            }
            else
            {
                try
                {
                    vlcControlMain.Stop();
                }
                catch (Exception)
                {
                }
                VlcContext.CloseAll();
            }
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            Connect();
        }

        private void trackBar2_ValueChanged(object sender, EventArgs e)
        {
            label2.Text = "Cache: " + (trackBar2.Value * 100).ToString() + " ms";
        }

        private void trackBar2_MouseUp(object sender, MouseEventArgs e)
        {
            Connect(trackBar2.Value * 100);
        }

        private void Connect(int CacheSize = 500)
        {
            try
            {
                this.vlcControlMain.Stop();
            }
            catch (Exception)
            {
            }
            intCacheSize = CacheSize;
            label2.Text = "Cache: " + CacheSize.ToString() + " ms";
            var media = new LocationMedia("http://tux2005.dyndns.org:8080/Video");
            media.AddOption(":http-reconnect");
            media.AddOption(":quiet-synchro");
            media.AddOption(":network-caching=" + CacheSize.ToString());
            media.AddOption(":ts-csa-ck=0123456789101112");
            this.vlcControlMain.Media = media;
            this.vlcControlMain.Play();
        }

        #endregion

        #region Sanuk

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            if (SanukSourceID != string.Empty)
            {
                PowerLevel _powerLevel;
                _powerLevel = (PowerLevel)trackBar1.Value;
                EventDataType data = new EventDataType();
                data.TargetClient = SanukSourceID;
                data.EventMessage = string.Format("Sanuk|{0}", _powerLevel);
                Reference.SendData(data);
                label1.Text = "Dildo-Level " + trackBar1.Value.ToString();
            }
        }

        private enum PowerLevel
        {
            p = 0 | 1,
            a = 2,
            b = 3,
            c = 4,
            d = 5,
            e = 6,
            f = 7,
            g = 8,
            h = 9,
            i = 10,
            j = 11,
            k = 12,
            l = 13,
            m = 14,
            n = 15,
            o = 16
        }

        private void MaxPowerLevel(int PowerLevel)
        {
            this.trackBar1.Maximum = PowerLevel;
        }

        #endregion

        #region Chat

        private void buttonChat_Click(object sender, EventArgs e)
        {
            ChatOpen();
        }

        public void ChatSendMessage(string TargetClient, string MessageText)
        {
            EventDataType data = new EventDataType();
            data.TargetClient = TargetClient;
            data.EventMessage = string.Format("Chat|{0}|", MessageText);
            Reference.NotifyServer(data);
        }

        private void ChatOpen()
        {
            if (frmChat == null)
            {
                frmChat = new Chat(this);
                frmChat.Show();
            }
            else
            {
                if (frmChat.IsDisposed)
                {
                    frmChat = new Chat(this);
                    frmChat.Show();
                }
                else
                {
                    frmChat.Show();
                }
            }
        }

        private void ChatNewMessage(string SourceClient, string MessageText)
        {
            ChatOpen();
            this.frmChat.SourceID = SourceClient;
            this.frmChat.NewMessage(MessageText);
        }

        #endregion

        private void VlcPlayer_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }
    }


}
